package cn.kgc.itrip.search.dao;

import cn.kgc.itrip.beans.common.ServerResponse;
import cn.kgc.itrip.search.model.Hotel;
import cn.kgc.itrip.util.Page;
import cn.kgc.itrip.util.PropertiesUtil;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.impl.XMLResponseParser;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 阿泽
 */
@Component
public class BaseDao {
    /**
     * solr连接对象
     */
    private HttpSolrClient httpSolrClient;

    /**
     * 无参构造
     */
    public BaseDao() {
        httpSolrClient = new HttpSolrClient(PropertiesUtil.getProperty("solr.url"));
        //设置过期时间
        httpSolrClient.setConnectionTimeout(500);
        //设置格式样式
        httpSolrClient.setParser(new XMLResponseParser());
    }

    public ServerResponse queryData(SolrQuery solrQuery, Integer pageNo, Integer pageSize, Class clazz) throws IOException, SolrServerException {
        /**
         * 如果没有页码我们认为走热门城市查询
         */
        if (pageNo == null || pageSize == null) {
            QueryResponse query = httpSolrClient.query(solrQuery);
            List<Hotel> beans = query.getBeans(clazz);
            return ServerResponse.createBySuccess(beans);
        }
        QueryResponse query = httpSolrClient.query(solrQuery);
        List<Hotel> hotels = query.getBeans(clazz);
        Page<Hotel> page = new Page<>(pageNo,pageSize,hotels.size());
        /*//设置总条数
        page.setTotal(hotels.size());
        //设置总页码
        Integer pageCount = (hotels.size() % pageSize == 0 ? hotels.size() / pageSize : hotels.size() / pageSize + 1);
        page.setPageSize(pageCount);*/
        //全部数据
        List<Hotel> rows = new ArrayList<>();
        for (int i = (pageNo - 1) * pageSize; i < pageNo * pageSize; i++) {
            if (i < hotels.size()) {
                rows.add(hotels.get(i));
            } else {
                break;
            }
        }
        page.setRows(rows);
        return ServerResponse.createBySuccess(page);
    }
}
